package common.spring.converter;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.util.Date;

/**
 * Created by luozongsheng on 20/12/2016.
 */
public class StringToDateConvert implements Converter<String, Date> {
    public StringToDateConvert() {
    }

    public Date convert(String params) {
        if(StringUtils.isBlank(params)) {
            return null;
        } else {
            params = StringUtils.trim(params);

            try {
                return DateUtils.parseDate(params, new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss"});
            } catch (ParseException var5) {
                long time = NumberUtils.toLong(params, 0L);
                return time > 0L?new Date(time):null;
            }
        }
    }
}
